package com.yachtar.property.idcard;

import android.content.Context;



import java.io.IOException;

import com.fri.idcread.idcread;

public class IdCardManager {
	private static IdCardManager mManager;
	private static Object lock = new Object();
	private ReaderListener listener;
	private idcread mIdRead;
	private Context context;
	private ReadThread mReadThread;

	// private ReaderSerialPort rsp;
	// protected OutputStream mOutputStream;
	// protected InputStream mInputStream;

	public interface ReaderListener {
		public void onRead(IDCard mIDCard);

		public void onReadThing();

		public void onReadError(String error);
	}

	private IdCardManager() {

	}

	public static IdCardManager getInstance() {
		if (mManager == null) {
			synchronized (lock) {
				if (mManager == null) {
					mManager = new IdCardManager();
				}
			}
		}
		return mManager;
	}

	public void openDevice(Context context) throws IOException {
		this.context = context;
		closeDevice();
		mIdRead = new idcread();
		mIdRead.init(context);
		try {
			Thread.sleep(500);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public void startRead(ReaderListener l) {
		this.listener = l;
		if (mReadThread != null) {
			mReadThread.isRun = false;
		}
		mReadThread = new ReadThread();
		mReadThread.isRun = true;
		mReadThread.start();
	}

	public void stopRead() {
		if (mReadThread != null) {
			mReadThread.isRun = false;
		}
	}

	public void closeDevice() {
		if (mReadThread != null) {
			mReadThread.isRun = false;
		}
		if (mIdRead != null) {
			mIdRead.close();
		}
	}

	private class ReadThread extends Thread {
		public boolean isRun;

		@Override
		public void run() {
			// TODO Auto-generated method stub
			while (isRun) {
				try {
					if (mIdRead != null) {
						IDCard mIDCard = mIdRead.duibi();
						if (mIDCard != null) {
							if (listener != null) {
								listener.onRead(mIDCard);
							}
						} else {
							if (listener != null) {
								listener.onReadThing();
							}
						}
						try {
							Thread.sleep(100);
						} catch (InterruptedException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					} else {
						if (listener != null) {
							listener.onReadError("mIRead is null");
						}
					}
				} catch (Exception e) {
					// TODO: handle exception
					e.printStackTrace();
					if (listener != null) {
						listener.onReadError(e.getMessage());
					}
				}

			}
		}
	}
}
